package com.seele.tigerwallet.ui.activtiy;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.j256.ormlite.dao.Dao;
import com.seele.tigerwallet.R;
import com.seele.tigerwallet.api.APIException;
import com.seele.tigerwallet.api.APIListCallBack;
import com.seele.tigerwallet.api.APIModule;
import com.seele.tigerwallet.api.APIObjectCallBack;
import com.seele.tigerwallet.api.BaseResult;
import com.seele.tigerwallet.async.Log;
import com.seele.tigerwallet.model.ContactsModel;
import com.seele.tigerwallet.model.UserInfo;
import com.seele.tigerwallet.ui.adapter.ContactsAdapter;
import com.seele.tigerwallet.ui.base.ToolbarBaseActivity;
import com.seele.tigerwallet.ui.manager.DaoManager;
import com.seele.tigerwallet.ui.utils.GsonUtil;
import com.seele.tigerwallet.ui.utils.SPUtils;
import com.seele.tigerwallet.ui.utils.SqlUtil;
import com.seele.tigerwallet.ui.views.SwipeItemLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import retrofit2.Call;

public class ContactsActivity extends ToolbarBaseActivity {


    private ContactsAdapter mContactsAdapter;
    private RecyclerView mRecyclerView;
    public static final int SOURCE_TRANSFER = 0X9632;
    //    private WalletAsyncTask mWalletAsyncTask;
    private List<ContactsModel> mContactsModels;
    private View mView;
    int flag;
    private int id;
    private int num = 50;


    public static void closeAllItems(RecyclerView recyclerView){
        for(int i=0;i<recyclerView.getChildCount();i++){
            View child = recyclerView.getChildAt(i);
            if(child instanceof SwipeItemLayout){
                SwipeItemLayout swipeItemLayout = (SwipeItemLayout) child;
                if(swipeItemLayout.isOpen())
                    swipeItemLayout.close();
            }
        }
    }

    @Override
    public int getContainerViewId() {
        return R.layout.activity_contacts;
    }

    @Override
    protected void initView() {
        if (!isRegistered()) {
            EventBus.getDefault().register(this);
        }



        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            flag = bundle.getInt(ContactsActivity.class.getSimpleName());
        }
        setTitle(R.string.contacts);

        setRightImg(R.drawable.icon_add);


        mView = View.inflate(this, R.layout.default_view, null);
        mRecyclerView = $f(R.id.contact_recyclerView);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.addOnItemTouchListener(new SwipeItemLayout.OnSwipeItemTouchListener(this));
        mContactsAdapter = new ContactsAdapter(R.layout.item_contacts);
        mRecyclerView.setAdapter(mContactsAdapter);


        //请求网络联系人
        getlinkman();

        mContactsAdapter.setonItemClickListener(new ContactsAdapter.OnItemClickListener() {
            @Override
            public void onDeleteClick(int position, ContactsModel item) {
                onDeleteFind(position, item);

            }

            @Override
            public void onItemClick(int position, ContactsModel item) {
                if (null == mContactsModels) {
                    return;
                }
                ContactsModel contactsModel = mContactsModels.get(position);
                if (flag == SOURCE_TRANSFER) {

                    String address = contactsModel.toaddr;
                    Intent intent = new Intent(ContactsActivity.this, TransferTokenActivity.class);
                    intent.putExtra(ContactsActivity.class.getSimpleName(), address);
                    setResult(RESULT_OK, intent);
                    finish();



                }

            }

            @Override
            public void onUpdateClick(final int position, ContactsModel item) {
                if (null!=mRecyclerView){
                    View child = mRecyclerView.getChildAt(position);
                    if(child instanceof SwipeItemLayout){
                        SwipeItemLayout swipeItemLayout = (SwipeItemLayout) child;
                        if(swipeItemLayout.isOpen())
                            swipeItemLayout.close();
                    }
                }
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Bundle bundleIntent = new Bundle();
                        bundleIntent.putSerializable(CreateContactsActivity.class.getSimpleName(), mContactsModels.get(position));
                        startActivity(CreateContactsActivity.class, bundleIntent);
                    }
                },100);
//                closeAllItems(mRecyclerView);

            }
        });
    }

    private void onDeleteFind(final int position, ContactsModel item) {
        APIModule
                .getApi()
                .defined(UserInfo.get().token, item.id + "", UserInfo.get().address)
                .enqueue(new APIObjectCallBack<BaseResult>() {

                    @Override
                    protected void onResponse(BaseResult response) {
                        if (null != response) {
                            UserInfo.get().token = response.token;
                            SPUtils.saveUserInfo(UserInfo.get());
                            mContactsAdapter.remove(position);
                        }
                    }

                    @Override
                    protected void onResponseError(APIException e) {
                        Toast.makeText(ContactsActivity.this, getResources().getString(R.string.delete_error), Toast.LENGTH_SHORT).show();

                    }

                    @Override
                    protected void onFailureError(Call<String> call, Throwable t) {
                        Toast.makeText(ContactsActivity.this, getResources().getString(R.string.delete_error), Toast.LENGTH_SHORT).show();

                    }


                });
    }

    @Override
    protected void onRightImg() {
        startActivity(CreateContactsActivity.class);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(ContactsModel event) {
        getlinkman();
    }


    private boolean isRegistered() {
        return EventBus.getDefault().isRegistered(this);
    }


    class WalletAsyncTask extends AsyncTask<Void, Void, List<ContactsModel>> {

        public WalletAsyncTask() {
            super();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected List<ContactsModel> doInBackground(Void... voids) {
            try {
                List<ContactsModel> contactsModels = DaoManager.getContactsDao().queryBuilder().where().eq("address", UserInfo.get().address).query();
                if (null != contactsModels) {
                    return contactsModels;
                }
            } catch (Exception e) {
                getlinkman();
                e.printStackTrace();
            }


            return null;
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }

        @Override
        protected void onPostExecute(List<ContactsModel> contactsModels) {
            if (null != contactsModels && contactsModels.size() > 0) {
                mContactsModels = contactsModels;
                mContactsAdapter.setNewData(mContactsModels);
                mContactsAdapter.notifyDataSetChanged();
            } else {
                setEmptyView();
            }


            super.onPostExecute(contactsModels);
        }
    }

    private void getlinkman() {
        String address = UserInfo.get().address;
        if (TextUtils.isEmpty(address)) {
            return;
        }

        APIModule
                .getApi()
                .getlinkman(id, num, address)
                .enqueue(new APIListCallBack<ContactsModel>() {
                    @Override
                    protected void onResponseError(APIException e) {
                        //查询本地数据
                        new WalletAsyncTask().execute();

                    }

                    @Override
                    protected void onFailureError(Call<String> call, Throwable t) {
                        //查询被动
                        new WalletAsyncTask().execute();
                    }

                    @Override
                    protected void onResponse(List<ContactsModel> response) {
                        try {
                            if (null != response && response.size() > 0) {
                                mContactsModels = response;
                                mContactsAdapter.setNewData(mContactsModels);
                                mContactsAdapter.notifyDataSetChanged();
                                for (ContactsModel mContactsModel : mContactsModels) {
                                    mContactsModel.address = UserInfo.get().address;
                                    //TODO 不知道为什么报错,后面的大神你来处理下
//                                    DaoManager.saveOrUpdate(mContactsModel);
                                }
                                saveOrUpdate();

                            } else {
                                setEmptyView();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                });

    }


    private void saveOrUpdate() {
        //保存数据
        if (null != mContactsModels && mContactsModels.size() > 0) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for (ContactsModel mContactsModel : mContactsModels) {
                        try {
                            List<ContactsModel> contactsModels = getContactsDao().queryBuilder().where().eq("contactsId", mContactsModel.id).query();
                            if (null != contactsModels && contactsModels.size() > 0) {
                                getContactsDao().updateId(mContactsModel, mContactsModel.id);
                                String sql = SqlUtil.updateContact(mContactsModel.toaddr,
                                        mContactsModel.address,
                                        mContactsModel.firstname,
                                        mContactsModel.lastname,
                                        mContactsModel.mail,
                                        mContactsModel.note,
                                        mContactsModel.phone,
                                        mContactsModel.id + "");
                                getContactsDao().updateRaw(sql);
                            } else {
                                getContactsDao().create(mContactsModel);
                            }


                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }


                }
            }).start();


        }


    }


    public Dao getContactsDao() {
        return DaoManager.getContactsDao();
    }

    private void setEmptyView() {
        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        if (null != mView) {
            mView.setLayoutParams(layoutParams);
            mContactsAdapter.setEmptyView(mView);
        }
    }

    @Override
    protected void onDestroy() {
        if (isRegistered()) {
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy();
    }
}
